package one.stand.controller.home;

import com.jmp.api.dto.UserInfoResponse;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import one.stand.dto.ConvertUtils;
import one.stand.dto.UserDto;
import one.stand.model.BusinessCard;
import one.stand.model.Menu;
import one.stand.model.ResultModel;
import one.stand.service.BusinessCardBaseService;
import one.stand.service.user.MenuService;
import one.stand.service.user.UserAdminService;
import one.stand.util.RequestContext;
import one.stand.util.RequestContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author cjr
 */
@Api(description = "我的")
@RequestMapping("user")
@RestController
public class UserController {

    @Autowired
    private UserAdminService userAdminService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private BusinessCardBaseService businessCardBaseService;

    @ApiOperation(value = "我的")
    @PostMapping("info")
    @SecurityAuthCheck
    public ResultModel<UserInfoResponse> info() {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        UserDto user = userAdminService.get(optUser.getUserId());
        List<Menu> openMenu = menuService.getOpenMenu(optUser.getUserId(), MenuService.TYPE_CRN_APP_NEW);
        List<String> openMenuCodes = ConvertUtils.list(openMenu, Menu::getPage).stream().filter(StringUtils::isNoneBlank).collect(Collectors.toList());

        String userName = user.getName();
        if(Objects.nonNull(optUser.getCardId())) {
            BusinessCard card = businessCardBaseService.getCustomer(optUser.getCardId());
            userName = card.getName();
        }

        UserInfoResponse response = UserInfoResponse.builder()
                .userId(optUser.getUserId())
                .userName(userName)
                .userImg(user.getUserImg())
                .auths(openMenuCodes)
                .build();
        return ResultModel.success(response);
    }
}
